package com.nativelaunchmanager
import android.graphics.Color
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.graphics.toColor
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.leosmart.MainActivity
import com.nativemodules.NativeLaunchManagerSpec
import androidx.core.graphics.toColorInt

class NativeLaunchManager(reactApplicationContext: ReactApplicationContext) :NativeLaunchManagerSpec(reactApplicationContext){
    @RequiresApi(Build.VERSION_CODES.O)
    override fun hide(theme: String?, promise: Promise?) {
        val mainActivity = MainActivity.getInstance()
        if (mainActivity != null) {
            mainActivity.runOnUiThread {
                mainActivity.dismissSplash(theme?.let { hexToColorObj(it) }?:Color.WHITE.toColor())
                promise?.resolve(null)
            }
        } else {
            promise?.reject("E_ACTIVITY_NULL", "MainActivity is null")
        }
    }
    @RequiresApi(Build.VERSION_CODES.O)
    fun hexToColorObj(hex: String): Color {
        val formatted = if (hex.startsWith("#")) hex else "#$hex"
        return Color.valueOf(formatted.toColorInt())
    }
    override fun show(promise: Promise?) {
        val mainActivity = MainActivity.getInstance()
        if (mainActivity != null) {
            mainActivity.runOnUiThread {
                mainActivity.createSplashView()
                promise?.resolve(true) }
        } else {
            promise?.reject("E_ACTIVITY_NULL", "MainActivity is null")
        }
    }
    override fun getName() = NAME
    companion object{
        const val NAME="NativeLaunchManager"
    }
}